﻿using amis6_api.Common;
using amis6_api.Dto;
using amis6_api.Model;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using amis6_api.Utils;

namespace amis6_api.Service
{
    public class UserFondsService
    {
        public List<FondsDto> GetUserFonds(User user)
        {
            using var conn = DbFactory.Db();
            List<Fonds> list = new List<Fonds>();
            if (user.U_IsManager)
            {
                list = conn.Query<Fonds>("SELECT * FROM t_Fonds").ToList();
            }
            else
            {
                var menuId = conn.Query<Guid>("select * from T_UserTempMenu where [GU_GUID]=@guid and MNU_Type='Object_Stable' and MNU_Parent is null;", new { guid = user.U_ID });
                string uid = UserPermissionUtil.GetUserPermission(user.U_ID);
                string sql =
                    $"select a.* from t_Fonds a right join (select DISTINCT left(GUP_ResourceID,36) fondsId from T_UserTempMenu where [GU_GUID] in {uid} and MNU_Type='Instance_Fonds') b  on b.fondsId=a.Fonds_ID;";
                list = conn.Query<Fonds>(sql).ToList();
            }


            var listDto = GetFondsDtos(list);
            return listDto;
        }

        public List<FondsDto> GetFondsDtos(List<Fonds> list)
        {
            var parent = list.Where(a => a.Fonds_Father == null).ToList();
            List<FondsDto> Fondss = new List<FondsDto>();
            foreach (var item in parent)
            {
                FondsDto FondsDto = new FondsDto(item);
                AddChild(FondsDto, list);
                Fondss.Add(FondsDto);
            }
            return Fondss;
        }

        private void AddChild(FondsDto FondsDto, List<Fonds> list)
        {
            if (list.All(a => a.Fonds_Father != FondsDto.Parent.Fonds_ID))
                return;
            else
            {
                var children = list.Where(a => a.Fonds_Father == FondsDto.Parent.Fonds_ID).ToList();
                FondsDto.Children = new List<FondsDto>();
                foreach (var item in children)
                {
                    FondsDto childDto = new FondsDto(item);

                    FondsDto.Children.Add(childDto);

                    AddChild(childDto, list);
                }
            }
        }
    }


}
